package org.example.l0;

import java.util.ArrayList;
import java.util.List;

public class generateParenthesis {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        dfs(new StringBuilder(), n, n, n, res);
        return res;
    }

    void dfs(StringBuilder builder,
             int n,
             int left,
             int right,
             List<String> res) {

        if (builder.length() == n << 1) {
            res.add(builder.toString());
            return;
        }

        if (left > 0) {
            dfs(builder.append("("), n, left - 1, right, res);
            builder.deleteCharAt(builder.length() - 1);
        }

        if (right > left) {
            dfs(builder.append(")"), n, left, right - 1, res);
            builder.deleteCharAt(builder.length() - 1);
        }
    }
}
